﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using myFinance.Models;
using myFinance.Models.ViewModels;
using System.Web.Helpers;
using System.IO;
using myFinance.BLL;

namespace myFinance.Controllers
{
    public class HomeController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("Sobre");
            var pessoa = PessoaBll.GetPessoa(User.Identity.Name);

			if (pessoa == null)
				return RedirectToAction("Cadastro", "Perfil");
            
			var username = User.Identity.Name;
			Session["nomeUsuario"] = username;

            var model = new AvatarViewModel();

            #region Apaga a imagem do avatar do temp, caso exista
            if (pessoa != null)
            {
                var filename = Path.Combine(Server.MapPath("~/Content/Temp"), username + ".jpg");
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
                filename = Path.Combine(Server.MapPath("~/Content/Temp"), User.Identity.Name + ".jpg");
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
                filename = Path.Combine(Server.MapPath("~/Content/Temp"), username + ".jpg");
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
                filename = Path.Combine(Server.MapPath("~/Content/Temp"), User.Identity.Name + ".jpg");
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
            }
            else
            {
                if (AvatarStream.Avatar != null)
                {
                    AvatarStream.Avatar = new WebImage(pessoa.Avatar);
                }
            }
            #endregion

            return View(model);
        }

        public ActionResult Sobre()
        {
            return View();
        }
    }
}
